<template>
  <div class="airconditioner-monitor">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>空调设备监控</h2>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-refresh" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 田字形布局的4个模块 -->
    <div class="monitor-grid">
      <!-- 第一个模块：参数设置（空调） -->
      <div class="grid-item parameter-settings">
        <!-- 顶部：左侧标题与状态，右侧下拉与参数配置按钮 -->
        <div class="module-header">
          <div class="module-left">
            <!-- 标题与状态文本：在线绿色，离线红色 -->
            <span class="device-title">空调</span>
            <span class="status-text" :class="deviceStatus.online ? 'online' : 'offline'">
              {{ deviceStatus.online ? '在线' : '离线' }}
            </span>
          </div>
          <div class="header-controls">
            <!-- 顶部下拉选择框，默认“区域控制器 - 空调设备_1” -->
            <el-select v-model="selectedDeviceIdent" size="mini" placeholder="区域控制器 - 空调设备_1" style="width: 260px;" @change="handleControllerChange">
              <el-option v-for="opt in controllerOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
            </el-select>
            <el-button type="primary" size="mini" @click="openParameterConfig">参数配置</el-button>
          </div>
        </div>

        <!-- 中间区域：左侧空调图标，右侧制热/制冷两个模块与运行模式 -->
        <div class="module-content">
          <div class="ac-settings">
            <!-- 左侧：简洁蓝色空调图标 -->
            <div class="ac-left">
              <i class="el-icon-s-platform ac-icon"></i>
            </div>
            <!-- 右侧：制热/制冷模块与运行模式 -->
            <div class="ac-right">
              <!-- 制热模块 -->
              <div class="mode-card heat">
                <i class="el-icon-sunny icon"></i>
                <div class="content">
                  <div class="title">制热设定</div>
                  <div class="value">{{ currentDevice ? currentDevice.hotSet : '--' }}℃</div>
                </div>
              </div>
              <!-- 制冷模块 -->
              <div class="mode-card cool">
                <i class="el-icon-cold-drink icon"></i>
                <div class="content">
                  <div class="title">制冷设定</div>
                  <div class="value">{{ currentDevice ? currentDevice.coldSet : '--' }}℃</div>
                </div>
              </div>
              <!-- 运行模式说明：单选框 -->
              <div class="run-mode">
                <div class="label">运行模式</div>
                <el-radio-group v-model="runMode">
                  <el-radio label="auto">自动模式</el-radio>
                  <el-radio label="manual">手动模式</el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 第二个模块：设备状态 -->
      <div class="grid-item device-status">
        <div class="module-header">
          <i class="el-icon-monitor"></i>
          <span>设备状态</span>
        </div>
        <div class="module-content">
          <div class="status-cards">
            <!-- 温度状态 -->
            <div class="status-card">
              <div class="progress-circle">
                <svg class="progress" width="160" height="160" viewBox="0 0 160 160">
                  <!-- 背景圆环 -->
                  <circle
                    class="progress-background"
                    cx="80"
                    cy="80"
                    r="70"
                    stroke-width="10"
                    fill="none"
                  />
                  <!-- 进度圆环 -->
                  <circle
                    class="progress-bar temperature"
                    cx="80"
                    cy="80"
                    r="70"
                    stroke-width="10"
                    fill="none"
                    :stroke-dasharray="getProgressCircumference()"
                    :stroke-dashoffset="getTemperatureProgress()"
                    transform="rotate(-90 80 80)"
                  />
                </svg>
                <div class="progress-content">
                  <div class="value">{{ deviceStatus.temperature }}°C</div>
                  <div class="label">温度</div>
                </div>
              </div>
              <div class="card-time">{{ deviceStatus.updateTime }}</div>
            </div>

            <!-- 能耗状态 -->
            <div class="status-card">
              <div class="progress-circle">
                <svg class="progress" width="160" height="160" viewBox="0 0 160 160">
                  <!-- 背景圆环 -->
                  <circle
                    class="progress-background"
                    cx="80"
                    cy="80"
                    r="70"
                    stroke-width="10"
                    fill="none"
                  />
                  <!-- 进度圆环 -->
                  <circle
                    class="progress-bar energy"
                    cx="80"
                    cy="80"
                    r="70"
                    stroke-width="10"
                    fill="none"
                    :stroke-dasharray="getProgressCircumference()"
                    :stroke-dashoffset="getEnergyProgress()"
                    transform="rotate(-90 80 80)"
                  />
                </svg>
                <div class="progress-content">
                  <div class="value">{{ deviceStatus.energy }}kW</div>
                  <div class="label">能耗</div>
                </div>
              </div>
              <div class="card-time">{{ deviceStatus.updateTime }}</div>
            </div>
          </div>

          <div class="device-info">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="info-label">设备ID:</span>
                  <span class="info-value">{{ deviceStatus.deviceId }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="info-label">运行状态:</span>
                  <el-tag :type="deviceStatus.running ? 'success' : 'danger'" size="small">
                    {{ deviceStatus.running ? '运行中' : '已停止' }}
                  </el-tag>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="info-label">连接状态:</span>
                  <el-tag :type="deviceStatus.online ? 'success' : 'danger'" size="small">
                    {{ deviceStatus.online ? '在线' : '离线' }}
                  </el-tag>
                </div>
              </el-col>
            </el-row>

            <!-- 设备控制按钮 -->
            <div class="device-controls">
              <el-button
                :type="deviceStatus.running ? 'danger' : 'success'"
                size="small"
                @click="toggleDevice"
                :loading="controlLoading"
              >
                {{ deviceStatus.running ? '停止空调' : '启动空调' }}
              </el-button>
              <el-button type="primary" size="small" @click="showControlPanel">
                控制面板
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 第三个模块：温湿度曲线 -->
      <div class="grid-item chart-module">
        <div class="module-header">
          <i class="el-icon-data-line"></i>
          <span>温湿度曲线</span>
          <div class="header-controls">
            <el-select v-model="chartTimeRange" size="mini" @change="updateChart">
              <el-option label="最近1小时" value="1h"></el-option>
              <el-option label="最近6小时" value="6h"></el-option>
              <el-option label="最近24小时" value="24h"></el-option>
              <el-option label="最近7天" value="7d"></el-option>
            </el-select>
          </div>
        </div>
        <div class="module-content">
          <div id="airConditionerChart" style="width: 100%; height: 300px;"></div>
        </div>
      </div>

      <!-- 第四个模块：运行日志 -->
      <div class="grid-item log-module">
        <div class="module-header">
          <i class="el-icon-document"></i>
          <span>运行日志</span>
          <div class="header-controls">
            <el-button type="text" size="mini" @click="clearLogs">清空日志</el-button>
          </div>
        </div>
        <div class="module-content">
          <div class="log-container" v-loading="logLoading">
            <div v-if="logs.length === 0 && !logLoading" class="no-data">
              暂无日志数据
            </div>
            <div v-for="(log, index) in logs" :key="index" class="log-item" :class="getLogClass(log.type)">
              <span class="log-time">{{ log.time }}</span>
              <el-tag :type="getLogTagType(log.type)" size="mini">{{ log.type }}</el-tag>
              <span class="log-device">{{ log.deviceName }}</span>
              <span class="log-message">{{ log.content }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 控制面板对话框 -->
    <el-dialog title="空调控制面板" :visible.sync="controlPanelVisible" width="500px">
      <div class="control-panel">
        <el-form :model="controlForm" label-width="100px">
          <el-form-item label="目标温度">
            <el-slider
              v-model="controlForm.targetTemp"
              :min="16"
              :max="30"
              :step="1"
              show-stops
              show-tooltip
            />
            <span class="temp-display">{{ controlForm.targetTemp }}°C</span>
          </el-form-item>
          <el-form-item label="风速档位">
            <el-radio-group v-model="controlForm.fanSpeed">
              <el-radio :label="1">低速</el-radio>
              <el-radio :label="2">中速</el-radio>
              <el-radio :label="3">高速</el-radio>
              <el-radio :label="0">自动</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="运行模式">
            <el-select v-model="controlForm.mode" placeholder="请选择运行模式">
              <el-option label="制冷" value="cool"></el-option>
              <el-option label="制热" value="heat"></el-option>
              <el-option label="除湿" value="dehumidify"></el-option>
              <el-option label="送风" value="fan"></el-option>
              <el-option label="自动" value="auto"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="controlPanelVisible = false">取 消</el-button>
        <el-button type="primary" @click="applyControl" :loading="controlLoading">应 用</el-button>
      </div>
    </el-dialog>

    <!-- 编辑详情弹窗：用于空调参数的编辑 -->
    <el-dialog
      title="编辑详情"
      :visible.sync="parameterConfigVisible"
      width="700px"
      :close-on-click-modal="false"
      :show-close="true"
    >
      <!-- 多列布局的表单 -->
      <el-form :model="editForm" ref="editFormRef" label-width="110px">
        <el-row :gutter="20">
          <!-- 设备类型：只读下拉，默认 空调 -->
          <el-col :span="12">
            <el-form-item label="设备类型">
              <el-select v-model="editForm.deviceType" disabled placeholder="空调">
                <el-option v-for="opt in deviceTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 所属库房：必填，只读下拉，默认 A 库房 -->
          <el-col :span="12">
            <el-form-item label="所属库房" required>
              <el-select v-model="editForm.storehouse" disabled placeholder="A 库房">
                <el-option v-for="opt in storehouseOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 设备名称：必填输入框 -->
          <el-col :span="12">
            <el-form-item label="设备名称" required>
              <el-input v-model="editForm.deviceName" placeholder="空调设备_1" />
            </el-form-item>
          </el-col>

          <!-- 设备编号：必填，只读下拉，默认 01 -->
          <el-col :span="12">
            <el-form-item label="设备编号" required>
              <el-select v-model="editForm.deviceNo" disabled placeholder="01">
                <el-option v-for="opt in deviceNoOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 制热设定：输入框，默认 14 -->
          <el-col :span="12">
            <el-form-item label="制热设定">
              <el-input v-model="editForm.heatSet" placeholder="14" />
            </el-form-item>
          </el-col>

          <!-- 制热回差：输入框，默认 0 -->
          <el-col :span="12">
            <el-form-item label="制热回差">
              <el-input v-model="editForm.heatDiff" placeholder="0" />
            </el-form-item>
          </el-col>

          <!-- 制冷设定：输入框，默认 24 -->
          <el-col :span="12">
            <el-form-item label="制冷设定">
              <el-input v-model="editForm.coolSet" placeholder="24" />
            </el-form-item>
          </el-col>

          <!-- 制冷回差：输入框，默认 0 -->
          <el-col :span="12">
            <el-form-item label="制冷回差">
              <el-input v-model="editForm.coolDiff" placeholder="0" />
            </el-form-item>
          </el-col>

          <!-- 关联传感器：下拉，默认 平均值 -->
          <el-col :span="12">
            <el-form-item label="关联传感器">
              <el-select v-model="editForm.sensorMode" placeholder="平均值">
                <el-option v-for="opt in sensorOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 修改方式：单选按钮组 -->
          <el-col :span="12">
            <el-form-item label="修改方式">
              <el-radio-group v-model="editForm.modifyMode">
                <el-radio label="single">本设备修改</el-radio>
                <el-radio label="batch">批量修改</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部操作按钮：右侧显示取消与确认 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="parameterConfigVisible = false">取 消</el-button>
        <el-button type="primary" :loading="editLoading" @click="confirmEdit">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getAirConditionerLogs,
  getAirConditionerStatus,
  getAirConditionerData,
  saveAirConditionerParameters,
  getAirConditionerParameters,
  getAirConditionerChart,
  controlAirConditioner,
  clearAirConditionerLogs,
  getAirConditionerManage,
  updateAirConditionerDevice
} from '@/api/archives/airconditioner'

export default {
  name: "AirConditionerMonitor",
  data() {
    return {
      // 参数设置表单
      parameterForm: {
        tempMin: 18.0,
        tempMax: 26.0,
        energyMin: 0.0,
        energyMax: 50.0
      },
      // 顶部选择与运行模式
      selectedDeviceIdent: '', // 选中的设备标识 ident
      controllerOptions: [],   // 下拉选项（alias + ident）
      currentDevice: null,     // 当前选中设备对象
      manageDevices: [],       // 设备管理列表缓存
      runMode: 'auto',
      // 设备状态数据
      deviceStatus: {
        temperature: 22.5,
        energy: 25.8,
        deviceId: "AC001",
        running: true,
        online: true,
        updateTime: "2025-05-21 10:30:25"
      },
      // 控制表单
      controlForm: {
        targetTemp: 22,
        fanSpeed: 2,
        mode: 'cool'
      },
      parameterLoading: false,
      controlLoading: false,
      controlPanelVisible: false,
      // 参数配置（编辑详情）弹窗显示状态
      parameterConfigVisible: false,
      // 编辑详情表单数据（默认值根据需求）
      editForm: {
        deviceType: '空调',           // 设备类型：空调
        storehouse: 'A库房',          // 所属库房：A 库房
        deviceName: '空调设备_1',      // 设备名称
        deviceNo: '01',               // 设备编号
        heatSet: '14',                // 制热设定
        heatDiff: '0',                // 制热回差
        coolSet: '24',                // 制冷设定
        coolDiff: '0',                // 制冷回差
        sensorMode: 'AVERAGE_VALUE',  // 关联传感器：平均值
        modifyMode: 'single'          // 修改方式：本设备修改
      },
      // 下拉选项：设备类型、库房、编号、传感器
      deviceTypeOptions: [
        { label: '空调', value: '空调' }
      ],
      storehouseOptions: [
        { label: 'A 库房', value: 'A库房' }
      ],
      deviceNoOptions: [
        { label: '01', value: '01' }
      ],
      sensorOptions: [
        { label: '平均值', value: 'AVERAGE_VALUE' },
        { label: '最大值', value: 'MAX_VALUE' },
        { label: '最小值', value: 'MIN_VALUE' },
        { label: '实时值', value: 'REALTIME_VALUE' }
      ],
      // 编辑确认按钮 loading
      editLoading: false,

      // 图表相关
      chart: null,
      chartTimeRange: '6h',
      chartData: {
        times: [],
        temperatures: [],
        energies: []
      },

      // 日志数据
      logs: [],
      logLoading: false,

      // 定时器
      dataTimer: null
    }
  },
  mounted() {
    this.initChart()
    // 先加载设备管理列表，再加载其余数据
    this.loadManageDevices().then(() => {
      this.loadData()
    })
    // 定时刷新数据
    this.timer = setInterval(() => {
      this.loadData()
    }, 30000) // 30秒刷新一次
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    // 构建POST请求的设备参数（与变送器模块一致）
    buildTransmitterPayload(extra = {}) {
      // 按后端要求传递：storeId、deviceTypeCode、deviceAddrCode、termId、storeCode
      // 注意：deviceTypeCode 固定为 '01'（与变送器一致）
      const d = this.currentDevice || {}
      return {
        storeId: d.storeId,
        deviceTypeCode: '01',
        deviceAddrCode: d.deviceAddrCode,
        termId: d.termId,
        storeCode: d.storeCode || (d.storeName ? String(d.storeName).charAt(0) : undefined),
        ...extra
      }
    },
    // 加载设备管理列表并初始化选择与页面显示
    async loadManageDevices() {
      try {
        const res = await getAirConditionerManage()
        if (res && (res.code === 200 || res.code === '200') && Array.isArray(res.data)) {
          const list = res.data
          this.manageDevices = list
          // 构建下拉选项：alias 作为label，ident作为value
          this.controllerOptions = list.map(item => ({ label: item.alias, value: item.ident }))

          // 选中设备：优先保留当前选择；否则默认选中第一个
          if (list.length > 0) {
            const keepIdent = this.selectedDeviceIdent
            const deviceToUse = keepIdent ? (list.find(d => d.ident === keepIdent) || list[0]) : list[0]
            this.selectedDeviceIdent = deviceToUse.ident
            this.currentDevice = deviceToUse

            // 根据设备状态字段 opStatus 填充在线/离线（opStatus=0 显示离线）
            this.deviceStatus.online = String(deviceToUse.opStatus) !== '0'

            // 页面卡片数据通过模板绑定 currentDevice 的 hotSet/coldSet 显示
          }
        } else {
          this.$message.warning('设备管理列表获取失败')
        }
      } catch (e) {
        console.error('获取设备管理列表失败：', e)
        this.$message.error('设备管理列表获取失败')
      }
    },

    // 处理顶部控制器切换事件（ElSelect change）
    // 入参 value 为选择设备的 ident
    handleControllerChange(value) {
      this.selectedDeviceIdent = value
      // 根据 ident 在缓存列表中查找并更新当前设备
      const selected = this.controllerOptions.find(o => o.value === value)
      const device = this.manageDevices.find(d => d.ident === value)
      if (device) {
        this.currentDevice = device
        this.deviceStatus.online = String(device.opStatus) !== '0'
      }

      // 刷新其他数据（日志、图表等）
      this.refreshData()

      const label = selected?.label || value
      this.$message({ message: `已切换到：${label}`, type: 'success', duration: 1500 })
    },

    // 打开参数配置弹窗，并根据当前设备填充表单
    openParameterConfig() {
      if (this.currentDevice) {
        this.editForm = {
          deviceType: this.currentDevice.deviceType || '空调',
          storehouse: this.currentDevice.storeName || 'A库房',
          deviceName: this.currentDevice.deviceName || '空调设备_1',
          deviceNo: this.currentDevice.deviceAddrCode || '01',
          heatSet: String(this.currentDevice.hotSet || '14'),
          heatDiff: String(this.currentDevice.hotSpan || '0'),
          coolSet: String(this.currentDevice.coldSet || '24'),
          coolDiff: String(this.currentDevice.coldSpan || '0'),
          sensorMode: this.currentDevice.refSensorNo || 'AVERAGE_VALUE',
          modifyMode: 'single'
        }
      }
      this.parameterConfigVisible = true
    },

    // 确认提交编辑详情
    async confirmEdit() {
      try {
        // 基础校验：必填字段检查（设备名称、所属库房、设备编号）
        if (!this.editForm.deviceName || !this.editForm.storehouse || !this.editForm.deviceNo) {
          this.$message.error('请填写必填项：所属库房、设备名称、设备编号')
          return
        }

        this.editLoading = true

        // 组装后端所需的 TransmitterDevice 数据结构
        // id 使用当前选中设备的 id
        if (!this.currentDevice || !this.currentDevice.id) {
          this.$message.error('当前设备信息缺失，无法保存')
          return
        }

        const payload = {
          // 设备类型编码（空调为 02）
          deviceTypeCode: '02',
          // 所属库房 ID
          storeId: this.currentDevice.storeId,
          // 设备名称（可编辑）
          deviceName: this.editForm.deviceName,
          // 设备编号（只读，来自当前设备地址码）
          deviceAddrCode: this.currentDevice.deviceAddrCode,
          // 制热设定与回差（可编辑）
          hotSet: this.editForm.heatSet,
          hotSpan: this.editForm.heatDiff,
          // 制冷设定与回差（可编辑）
          coldSet: this.editForm.coolSet,
          coldSpan: this.editForm.coolDiff,
          // 关联传感器（下拉）
          refSensorNo: this.editForm.sensorMode,
          // 修改方式：本设备修改=0，批量修改=1
          modStatus: this.editForm.modifyMode === 'single' ? 0 : 1,
          // 终端 ID
          termId: this.currentDevice.termId,
          // 设备类型名称（空调）
          deviceType: this.currentDevice.deviceType || '空调'
        }

        const res = await updateAirConditionerDevice(this.currentDevice.id, payload)
        if (res && (res.code === 200 || res.code === '200')) {
          // 保存成功后，同步更新当前设备与缓存列表，保持页面联动数据一致
          const updated = {
            ...this.currentDevice,
            deviceName: payload.deviceName,
            hotSet: payload.hotSet,
            hotSpan: payload.hotSpan,
            coldSet: payload.coldSet,
            coldSpan: payload.coldSpan,
            refSensorNo: payload.refSensorNo
          }
          this.currentDevice = updated
          this.manageDevices = this.manageDevices.map(d => d.id === updated.id ? updated : d)

          this.$message.success('编辑详情已保存')
          this.parameterConfigVisible = false
        } else {
          this.$message.error('保存失败：' + (res?.msg || '后端返回异常'))
        }
      } catch (e) {
        console.error('保存编辑详情失败：', e)
        this.$message.error('保存失败，请稍后重试')
      } finally {
        this.editLoading = false
      }
    },
    // 获取圆环周长
    getProgressCircumference() {
      const radius = 70;
      return 2 * Math.PI * radius;
    },

    // 计算温度进度
    getTemperatureProgress() {
      const circumference = this.getProgressCircumference();
      const maxTemp = 35; // 最大温度值
      const progress = (this.deviceStatus.temperature / maxTemp);
      return circumference * (1 - progress);
    },

    // 计算能耗进度
    getEnergyProgress() {
      const circumference = this.getProgressCircumference();
      const maxEnergy = 100; // 最大能耗值
      const progress = (this.deviceStatus.energy / maxEnergy);
      return circumference * (1 - progress);
    },

    // 加载所有数据
    async loadData() {
      await Promise.all([
        this.loadDeviceLogs(),
        this.loadDeviceStatus(),
        this.loadParameters(),
        this.loadChartData()
      ])
    },

    // 加载设备运行日志
    async loadDeviceLogs() {
      try {
        this.logLoading = true
        // 使用POST设备参数调用日志接口
        const response = await getAirConditionerLogs(this.buildTransmitterPayload())
        if (response.code === 200 && response.data) {
          // 处理API返回的日志数据
          this.logs = response.data.map(log => ({
            id: log.id,
            time: log.createTime,
            type: this.getLogTypeText(log.logType),
            content: log.deviceOpLog,
            deviceName: log.deviceName,
            status: log.status || '1',
            storeId: log.storeId,
            termId: log.termId,
            deviceTypeCode: log.deviceTypeCode,
            deviceAddrCode: log.deviceAddrCode,
            timeStamp: log.timeStamp
          }))
        } else {
          this.logs = []
          this.$message.warning('获取日志数据失败')
        }
      } catch (error) {
        console.error('加载设备日志失败:', error)
        this.$message.error('加载设备日志失败: ' + error.message)
        // 使用模拟数据作为备用
        this.logs = [
          {
            time: '2025-05-21 10:30:25',
            type: '信息',
            content: '空调设备启动成功',
            deviceName: '中央空调01',
            status: '正常'
          }
        ]
      } finally {
        this.logLoading = false
      }
    },

    // 加载设备状态
    async loadDeviceStatus() {
      try {
        // 模拟数据更新
        this.deviceStatus.temperature = (Math.random() * 8 + 18).toFixed(1)
        this.deviceStatus.energy = (Math.random() * 40 + 10).toFixed(1)
        this.deviceStatus.updateTime = new Date().toLocaleString()
      } catch (error) {
        console.error('加载设备状态失败:', error)
      }
    },

    // 加载参数设置
    async loadParameters() {
      try {
        // 暂时使用默认参数
      } catch (error) {
        console.error('加载参数设置失败:', error)
      }
    },

    // 初始化图表
     initChart() {
       this.chart = echarts.init(document.getElementById('airConditionerChart'))

       const option = {
         title: {
           text: '温湿度趋势',
           textStyle: {
             fontSize: 14,
             color: '#333'
           }
         },
         tooltip: {
           trigger: 'axis',
           axisPointer: {
             type: 'cross'
           }
         },
         legend: {
           data: ['温度', '湿度'],
           bottom: 10
         },
         grid: {
           left: '3%',
           right: '4%',
           bottom: '15%',
           containLabel: true
         },
         xAxis: {
           type: 'category',
           boundaryGap: false,
           data: this.chartData.times
         },
         yAxis: [
           {
             type: 'value',
             name: '温度(°C)',
             position: 'left',
             axisLabel: {
               formatter: '{value}°C'
             }
           },
           {
             type: 'value',
             name: '湿度(%)',
             position: 'right',
             axisLabel: {
               formatter: '{value}%'
             }
           }
         ],
         series: [
           {
             name: '温度',
             type: 'line',
             yAxisIndex: 0,
             data: this.chartData.temperatures,
             smooth: true,
             itemStyle: {
               color: '#ff6b6b'
             }
           },
           {
             name: '湿度',
             type: 'line',
             yAxisIndex: 1,
             data: this.chartData.humidities,
             smooth: true,
             itemStyle: {
               color: '#4ecdc4'
             }
           }
         ]
       }

       this.chart.setOption(option)
     },

    // 更新图表
    updateChart() {
      this.loadChartData()
    },

    // 加载图表数据
    async loadChartData() {
      try {
        console.log('=== 开始加载空调温湿度曲线数据 ===')
        console.log('时间范围:', this.chartTimeRange)
        // 使用POST设备参数调用曲线接口（可附加时间范围）
        const response = await getAirConditionerChart(this.buildTransmitterPayload({ timeRange: this.chartTimeRange }))

        console.log('=== 空调温湿度曲线API响应 ===')
        console.log('完整响应:', response)
        console.log('响应类型:', typeof response)
        console.log('code值:', response?.code, '类型:', typeof response?.code)
        console.log('data值:', response?.data, '是否为数组:', Array.isArray(response?.data))

        // 检查响应数据结构 - 支持字符串和数字类型的200
        if (response && (response.code === '200' || response.code === 200 || response.code == 200) && response.data && Array.isArray(response.data)) {
          console.log('=== 开始处理空调温湿度曲线数据 ===')
          console.log('原始数据条数:', response.data.length)

          const times = []
          const temperatures = []
          const humidities = []

          response.data.forEach((item, index) => {
            console.log(`处理第${index + 1}条曲线数据:`, item)
            times.push(item.time || '未知时间')
            temperatures.push(parseFloat(item.tem) || 0)
            humidities.push(parseFloat(item.hum) || 0)
          })

          this.chartData = { times, temperatures, humidities }

          console.log('=== 处理后的图表数据 ===')
          console.log('时间轴:', times)
          console.log('温度数据:', temperatures)
          console.log('湿度数据:', humidities)

          // 更新图表
          if (this.chart) {
            this.chart.setOption({
              xAxis: {
                data: times
              },
              series: [
                { data: temperatures },
                { data: humidities }
              ]
            })
          }

          this.$message({
            message: `成功加载 ${response.data.length} 个数据点的空调温湿度曲线`,
            type: 'success',
            duration: 2000
          })
        } else {
          // 如果API返回格式不符合预期，使用模拟数据
          console.warn('=== 空调温湿度曲线API返回数据格式异常，使用模拟数据 ===')
          console.warn('响应对象:', response)

          this.generateMockChartData()

          this.$message({
            message: '空调温湿度曲线数据格式异常，显示模拟数据',
            type: 'warning',
            duration: 3000
          })
        }
      } catch (error) {
        console.error('=== 空调温湿度曲线API请求失败 ===')
        console.error('错误详情:', error)
        console.error('错误类型:', error.constructor.name)
        console.error('错误消息:', error.message)

        // 检查是否是axios响应拦截器返回的错误
        if (error === 'error' || (typeof error === 'string' && error.includes('error'))) {
          console.warn('=== 可能是响应拦截器问题，使用模拟数据 ===')
          this.$message({
            message: '空调温湿度曲线数据格式问题，请检查后端返回的code字段类型',
            type: 'warning',
            duration: 3000
          })
        } else {
          this.$message({
            message: '加载空调温湿度曲线失败，显示模拟数据',
            type: 'error',
            duration: 3000
          })
        }

        // 发生错误时使用模拟数据
        this.generateMockChartData()
      }
    },

    // 处理API返回的图表数据
    processChartData(data) {
      console.log('API返回的数据:', data)
      const times = []
      const temperatures = []
      const energies = []

      if (data && Array.isArray(data) && data.length > 0) {
        data.forEach(item => {
          console.log('处理数据项:', item)
          // 根据时间范围格式化时间显示
          const time = new Date(item.createTime || item.time)
          let timeLabel = ''

          if (this.chartTimeRange === '1h' || this.chartTimeRange === '6h') {
            timeLabel = time.getHours().toString().padStart(2, '0') + ':' + time.getMinutes().toString().padStart(2, '0')
          } else if (this.chartTimeRange === '24h') {
            timeLabel = time.getHours().toString().padStart(2, '0') + ':00'
          } else {
            timeLabel = (time.getMonth() + 1) + '/' + time.getDate()
          }

          times.push(timeLabel)
          temperatures.push(parseFloat(item.temperature || item.temp || 0).toFixed(1))
          energies.push(parseFloat(item.energy || item.power || 0).toFixed(1))
        })
      } else {
        console.warn('API返回数据为空或格式不正确，使用模拟数据')
        this.generateMockChartData()
        return
      }

      console.log('处理后的图表数据:', { times, temperatures, energies })
      this.chartData = { times, temperatures, energies }

      if (this.chart) {
        this.chart.setOption({
          xAxis: {
            data: times
          },
          series: [
            { data: temperatures },
            { data: energies }
          ]
        })
      }
    },

    // 生成模拟图表数据
     generateMockChartData() {
       const now = new Date()
       const times = []
       const temperatures = []
       const humidities = []

       // 根据时间范围生成不同数量的数据点
       let dataPoints = 24 // 默认24小时
       let interval = 60 * 60 * 1000 // 1小时间隔

       switch (this.chartTimeRange) {
         case '1h':
           dataPoints = 12
           interval = 5 * 60 * 1000 // 5分钟间隔
           break
         case '6h':
           dataPoints = 12
           interval = 30 * 60 * 1000 // 30分钟间隔
           break
         case '24h':
           dataPoints = 24
           interval = 60 * 60 * 1000 // 1小时间隔
           break
         case '7d':
           dataPoints = 7
           interval = 24 * 60 * 60 * 1000 // 1天间隔
           break
       }

       for (let i = dataPoints - 1; i >= 0; i--) {
         const time = new Date(now.getTime() - i * interval)
         let timeLabel = ''

         if (this.chartTimeRange === '1h' || this.chartTimeRange === '6h') {
           timeLabel = time.getHours().toString().padStart(2, '0') + ':' + time.getMinutes().toString().padStart(2, '0')
         } else if (this.chartTimeRange === '24h') {
           timeLabel = time.getHours().toString().padStart(2, '0') + ':00'
         } else {
           timeLabel = (time.getMonth() + 1) + '/' + time.getDate()
         }

         times.push(timeLabel)
         temperatures.push((Math.random() * 10 + 20).toFixed(1))
         humidities.push((Math.random() * 30 + 40).toFixed(1))
       }

       this.chartData = { times, temperatures, humidities }

       if (this.chart) {
         this.chart.setOption({
           xAxis: {
             data: times
           },
           series: [
             { data: temperatures },
             { data: humidities }
           ]
         })
       }
     },

    // 保存参数设置
    saveParameters() {
      this.parameterLoading = true
      setTimeout(() => {
        this.parameterLoading = false
        this.$modal.msgSuccess('参数设置保存成功')
      }, 1000)
    },

    // 重置参数
    resetParameters() {
      this.parameterForm = {
        tempMin: 18.0,
        tempMax: 26.0,
        energyMin: 0.0,
        energyMax: 50.0
      }
    },

    // 刷新数据：同时刷新设备管理列表并保留当前选择
    async refreshData() {
      await this.loadManageDevices()
      // 其他数据刷新保持原有逻辑
      this.loadDeviceStatus()
      this.loadChartData()
      this.loadDeviceLogs()
      this.$message({
        message: '数据已刷新',
        type: 'success',
        duration: 2000
      })
    },

    // 切换设备状态
    async toggleDevice() {
      try {
        this.controlLoading = true
        // 模拟设备控制
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.deviceStatus.running = !this.deviceStatus.running
        this.$message({
          message: this.deviceStatus.running ? '空调已启动' : '空调已停止',
          type: 'success'
        })
      } catch (error) {
        this.$message.error('设备控制失败')
      } finally {
        this.controlLoading = false
      }
    },

    // 显示控制面板
    showControlPanel() {
      this.controlPanelVisible = true
    },

    // 应用控制设置
    async applyControl() {
      try {
        this.controlLoading = true
        // 模拟控制应用
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.$message.success('控制设置已应用')
        this.controlPanelVisible = false
      } catch (error) {
        this.$message.error('控制设置应用失败')
      } finally {
        this.controlLoading = false
      }
    },

    // 清空日志
    async clearLogs() {
      try {
        await this.$confirm('确认清空所有运行日志？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.logs = []
        this.$message.success('日志已清空')
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('清空日志失败')
        }
      }
    },

    // 获取日志类型文本
    getLogTypeText(logType) {
      const typeMap = {
        '1': '信息',
        '2': '警告',
        '3': '错误',
        '4': '调试'
      }
      return typeMap[logType] || '信息'
    },

    // 获取日志样式类
    getLogClass(type) {
      const classMap = {
        '信息': 'log-info',
        '警告': 'log-warning',
        '错误': 'log-error',
        '调试': 'log-debug'
      }
      return classMap[type] || 'log-info'
    },

    // 获取日志标签类型
    getLogTagType(type) {
      const typeMap = {
        '信息': 'info',
        '警告': 'warning',
        '错误': 'danger',
        '调试': 'success'
      }
      return typeMap[type] || 'info'
    },

    // 清空日志
    async clearLogs() {
      try {
        await this.$confirm('确认清空所有运行日志？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 调用API清空日志
        const response = await clearAirConditionerLogs()
        if (response.code === 200) {
          this.logs = []
          this.$message.success('日志已清空')
        } else {
          this.$message.error('清空日志失败: ' + response.msg)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('清空日志失败:', error)
          this.$message.error('清空日志失败')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.airconditioner-monitor {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .monitor-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 20px;

    .grid-item {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
      }

      .module-header {
        padding: 15px 20px;
        border-bottom: 1px solid #ebeef5;
        display: flex;
        align-items: center;

        i {
          margin-right: 8px;
          font-size: 18px;
          color: #409EFF;
        }

        span {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        }

        .header-controls {
          margin-left: auto;
        }
      }

      .module-content {
        padding: 20px;
      }
    }

    // 参数设置样式
    .parameter-settings {
      /* 顶部标题与状态样式 */
      .module-left {
        display: flex;
        align-items: center;
        gap: 8px;
      }
      .device-title { font-size: 16px; font-weight: 500; }
      .status-text { font-size: 14px; font-weight: 500; }
      .status-text.online { color: #67c23a; }
      .status-text.offline { color: #f56c6c; }

      /* 中间布局：空调图标 + 设定卡片 */
      .ac-settings { display: flex; align-items: stretch; gap: 16px; }
      .ac-left {
        width: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: linear-gradient(135deg, #e8f3ff, #f5faff);
        border: 1px solid #dbe9f8;
        border-radius: 8px;
      }
      .ac-icon { font-size: 36px; color: #409eff; }
      .ac-right { flex: 1; display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: auto auto; gap: 16px; }
      .mode-card {
        display: flex;
        align-items: center;
        background: #fff;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        padding: 12px 14px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.06);
        .icon { font-size: 24px; margin-right: 12px; }
        .content { display: flex; flex-direction: column; }
        .title { font-size: 14px; color: #606266; }
        .value { font-size: 26px; font-weight: 700; color: #303133; }
      }
      .mode-card.heat { border-color: rgba(245,108,108,0.35); background: linear-gradient(180deg, rgba(245,108,108,0.08), rgba(245,108,108,0.03)); }
      .mode-card.heat .icon { color: #f56c6c; }
      .mode-card.cool { border-color: rgba(64,158,255,0.35); background: linear-gradient(180deg, rgba(64,158,255,0.08), rgba(64,158,255,0.03)); }
      .mode-card.cool .icon { color: #409eff; }

      .run-mode {
        grid-column: 1 / span 2;
        background: #fff;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        padding: 12px 14px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .run-mode .label { font-size: 14px; color: #606266; }
      .parameter-card {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        transition: all 0.3s ease;

        &:hover {
          background: #f0f2f5;
        }

        .card-header {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          .icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;

            &.temperature {
              background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
              color: white;
            }

            &.energy {
              background: linear-gradient(135deg, #f39c12, #f1c40f);
              color: white;
            }

            i {
              font-size: 18px;
            }
          }

          .title {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
          }
        }

        .range-value {
          font-size: 14px;
          color: #606266;
          margin-bottom: 15px;

          &.energy {
            color: #f39c12;
          }
        }

        .input-group {
          display: flex;
          gap: 10px;

          .el-input-number {
            flex: 1;
          }
        }
      }

      .action-buttons {
        display: flex;
        gap: 10px;
        margin-top: 20px;
      }
    }

    // 设备状态样式
    .device-status {
      .status-cards {
        display: flex;
        justify-content: space-around;
        align-items: center;
        margin-bottom: 20px;
        padding: 20px 0;

        .status-card {
          text-align: center;

          .progress-circle {
            position: relative;
            display: inline-block;
            margin-bottom: 15px;

            .progress {
              transform: rotate(-90deg);
              filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
            }

            .progress-background {
              stroke: #e9ecef;
              stroke-linecap: round;
            }

            .progress-bar {
              transition: all 0.8s cubic-bezier(0.4, 0, 0.2, 1);
              stroke-linecap: round;

              &.temperature {
                stroke: #409eff;
                filter: drop-shadow(0 0 2px rgba(64, 158, 255, 0.5));
              }

              &.energy {
                stroke: #f56c6c;
                filter: drop-shadow(0 0 2px rgba(245, 108, 108, 0.5));
              }
            }

            .progress-content {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              text-align: center;
              transition: all 0.3s ease;

              .value {
                font-size: 28px;
                font-weight: bold;
                line-height: 1.2;
                background: linear-gradient(45deg, #303133, #606266);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                transition: all 0.3s ease;
              }

              .label {
                font-size: 14px;
                color: #909399;
                margin-top: 5px;
                opacity: 0.8;
                transition: all 0.3s ease;
              }
            }

            &:hover {
              .progress-content {
                transform: translate(-50%, -52%);

                .value {
                  transform: scale(1.05);
                }

                .label {
                  opacity: 1;
                }
              }
            }
          }

          .card-time {
            font-size: 12px;
            color: #909399;
            margin-top: 5px;
          }
        }
      }

      .device-info {
        background: #f5f7fa;
        border-radius: 6px;
        padding: 15px;
        margin-top: 10px;
        transition: all 0.3s ease;

        &:hover {
          background: #f0f2f5;
        }

        .info-item {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          &:last-child {
            margin-bottom: 0;
          }

          .info-label {
            font-size: 14px;
            color: #909399;
            margin-right: 8px;
            min-width: 80px;
          }

          .info-value {
            font-size: 14px;
            color: #303133;
            font-weight: 500;
          }
        }

        .device-controls {
          margin-top: 15px;
          display: flex;
          gap: 10px;
        }
      }
    }

    // 日志模块样式
    .log-module {
      .log-container {
        max-height: 300px;
        overflow-y: auto;

        .no-data {
          text-align: center;
          color: #909399;
          padding: 40px 0;
        }

        .log-item {
          padding: 8px 12px;
          border-left: 3px solid #e4e7ed;
          margin-bottom: 8px;
          background: #f8f9fa;
          border-radius: 4px;
          transition: all 0.3s ease;

          &:hover {
            background: #f0f2f5;
          }

          &.log-info {
            border-left-color: #409eff;
          }

          &.log-warning {
            border-left-color: #e6a23c;
          }

          &.log-error {
            border-left-color: #f56c6c;
          }

          .log-time {
            font-size: 12px;
            color: #909399;
            margin-right: 10px;
          }

          .log-device {
            font-size: 12px;
            color: #606266;
            margin: 0 10px;
          }

          .log-message {
            font-size: 13px;
            color: #303133;
          }
        }
      }
    }
  }

  // 控制面板样式
  .control-panel {
    .temp-display {
      margin-left: 10px;
      font-weight: bold;
      color: #409eff;
    }
  }
}

// 深度选择器修复
:deep(.el-tag) {
  &.el-tag--success {
    background-color: #f0f9ff;
    border-color: #b3d8ff;
    color: #409eff;
  }

  &.el-tag--danger {
    background-color: #fef0f0;
    border-color: #fbc4c4;
    color: #f56c6c;
  }
}
</style>